package com.dl.dw;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.PixelFormat;
import android.media.ImageReader;
import android.media.projection.MediaProjection;
import android.media.projection.MediaProjectionManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;

import com.blankj.utilcode.util.ConvertUtils;
import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.ScreenUtils;
import com.blankj.utilcode.util.ThreadUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.dl.dw.capture.ScreenCaptureService;
import com.dl.dw.databinding.ActivityMainBinding;
import com.dl.dw.event.ScanResultEvent;
import com.dl.dw.utils.OverlayUtil;
import com.dl.dw.vo.QuestionVO;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.mlkit.vision.text.Text;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends AppCompatActivity {

    private ActivityMainBinding binding;

    TextView showTextView;
    private void prepareOverlay() {
        showTextView = new TextView(this);
        showTextView.setText("Hello World");
        WindowManager.LayoutParams params = new WindowManager.LayoutParams(
                ConvertUtils.dp2px(300),
                ConvertUtils.dp2px(100),
                WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
                PixelFormat.TRANSLUCENT);
        params.gravity = Gravity.TOP | Gravity.RIGHT;

        OverlayUtil.showOverlay(this, showTextView,params);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        BottomNavigationView navView = findViewById(R.id.nav_view);
        AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
                R.id.navigation_home, R.id.navigation_dashboard, R.id.navigation_notifications)
                .build();
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_activity_main);
        NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
        NavigationUI.setupWithNavController(binding.navView, navController);




        //基础权限
        ActivityCompat.requestPermissions(this, new String[]{"android.permission.WRITE_EXTERNAL_STORAGE",
                "android.permission.READ_EXTERNAL_STORAGE"}, 10);

        //悬浮层准备
        prepareOverlay();

        //图文识别准备
        //prepareTessTwoImage2Text();

        boolean isDataReady=prepareData();
        if(isDataReady){
            //开始截屏并传给service图片识别
            takeScreenShot();
            //开始轮询匹配
            startMatch();
        }else{
            //测试写法，可优化
            ToastUtils.showLong("数据准备中，请等待十秒钟再重新打开app");
        }
    }

    String currentContent = "";//当前图片解析出来的内容

    //**************接收数据并匹配**************
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(ScanResultEvent event) {
        currentContent = event.getContent();
    }

    private void startMatch() {
        //定时器1秒执行一次
        Timer timer = new Timer();
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                if(TextUtils.isEmpty(currentContent)){
                    return;
                }
                for (QuestionVO questionVO : App.getInstance().questionVOS) {
                    int subSize= Math.min(questionVO.getQuestionContent().length(), 5);
                    if (currentContent.contains(questionVO.getQuestionContent().substring(0, subSize))) {
//                        ToastUtils.showLong(questionVO.getAnswer());
                        showTextView.post(new Runnable() {
                            @Override
                            public void run() {
                                showTextView.setText(questionVO.getAnswer());
                            }
                        });
//                        showTextView.setText(questionVO.getAnswer());
                        return;
                    }
                }
                for (QuestionVO questionVO : App.getInstance().questionVOS2) {
                    int subSize= Math.min(questionVO.getQuestionContent().length(), 5);
                    if (currentContent.contains(questionVO.getQuestionContent().substring(0, subSize))) {
//                        ToastUtils.showLong(questionVO.getAnswer());
                        showTextView.post(new Runnable() {
                            @Override
                            public void run() {
                                showTextView.setText(questionVO.getAnswer());
                            }
                        });
//                        showTextView.setText(questionVO.getAnswer());
                        return;
                    }
                }
            }
        };
        timer.schedule(task, 0, 1000);
    }
    //**************接收数据并匹配**************

    @Override
    public void onStart() {
        super.onStart();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    public void onStop() {
        super.onStop();
//        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    //*************************************系统截屏*************************************
    MediaProjectionManager mMediaProjectionManager = null;
    //开始截屏
    public void takeScreenShot() {
        // 系统截屏
        mMediaProjectionManager = (MediaProjectionManager) getApplication().getSystemService(Context.MEDIA_PROJECTION_SERVICE);
        startActivityForResult(mMediaProjectionManager.createScreenCaptureIntent(), 1111);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (requestCode == 1111 && resultCode == RESULT_OK) {
            //接收截屏数据
            startService(ScreenCaptureService.getStartIntent(this, resultCode, data));
        }

        super.onActivityResult(requestCode, resultCode, data);
    }
    //*************************************系统截屏*************************************

    //*************************************提取转化数据*************************************

    private boolean prepareData() {
        App.getInstance().questionVOS = LocalDataBox.getQuestionList();
        //读取excel
        if (ObjectUtils.isEmpty(App.getInstance().questionVOS)) {
            ThreadUtils.getIoPool().execute(new Runnable() {
                @Override
                public void run() {
                    prepareQuestionData();
                }
            });
            return false;
        }
        App.getInstance().questionVOS2 = LocalDataBox.getQuestion2List();
        if (ObjectUtils.isEmpty(App.getInstance().questionVOS2)) {
            ThreadUtils.getIoPool().execute(new Runnable() {
                @Override
                public void run() {
                    prepareQuestionData2();
                }
            });
            return false;
        }

        return true;
    }

    private void prepareQuestionData() {
        InputStreamReader is = null;
        List<QuestionVO> questionList = new ArrayList<>();
        try {
            is = new InputStreamReader(getResources().openRawResource(R.raw.question));
            BufferedReader reader = new BufferedReader(is);
            String line;
            QuestionVO questionVO = new QuestionVO();
            while ((line = reader.readLine()) != null) {
                if (line.contains("正确答案（点")) {
                    questionVO.setAnswer(line);
                    questionList.add(questionVO);
                    questionVO = new QuestionVO();
                    continue;
                }
                //正确答案那行也包含ABCDEF，所以要排除
                if (line.contains("A.") || line.contains("B.") || line.contains("C.")
                        || line.contains("D.") || line.contains("E.") || line.contains("F.")) {
                    if (ObjectUtils.isEmpty(questionVO.getAnswerList())) {
                        questionVO.setAnswerList(new ArrayList<>());
                    }
                    questionVO.getAnswerList().add(line);
                    continue;
                }
                questionVO.setQuestionContent(line);
//                Log.d("line -->",line==null?"null":line);
            }
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
            Log.d("line -->", e.getMessage());
        }
        App.getInstance().questionVOS = questionList;
        LocalDataBox.setQuestionList(questionList);
    }
    private void prepareQuestionData2() {
        InputStreamReader is = null;
        List<QuestionVO> questionList = new ArrayList<>();
        try {
            is = new InputStreamReader(getResources().openRawResource(R.raw.question2));
            BufferedReader reader = new BufferedReader(is);
            String line;
            QuestionVO questionVO = new QuestionVO();
            while ((line = reader.readLine()) != null) {
                if (line.contains("单选题") || line.contains("多选题") || line.contains("是非题")) {
                    continue;
                }
                if (line.contains("答案：")) {
                    questionVO.setAnswer(line);
                    questionList.add(questionVO);
                    questionVO = new QuestionVO();
                    continue;
                }
                //正确答案那行也包含ABCDEF，所以要排除
                if (line.contains("A.") || line.contains("B.") || line.contains("C.")
                        || line.contains("D.") || line.contains("E.") || line.contains("F.")) {
                    if (ObjectUtils.isEmpty(questionVO.getAnswerList())) {
                        questionVO.setAnswerList(new ArrayList<>());
                    }
                    questionVO.getAnswerList().add(line);
                    continue;
                }
                questionVO.setQuestionContent(line);
//                Log.d("line -->",line==null?"null":line);
            }
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
            Log.d("line -->", e.getMessage());
        }
        App.getInstance().questionVOS2 = questionList;
        LocalDataBox.setQuestion2List(questionList);
    }

    //*************************************提取转化数据*************************************


    //*************************************tess-two方式的图文识别准备（已弃用）*************************************
    //implementation 'com.rmtheis:tess-two:9.1.0'
    //***********准备区域
//    @Deprecated
//    private void prepareTessTwoImage2Text(){
//        if (PackageManager.PERMISSION_GRANTED ==
//                ContextCompat.checkSelfPermission(this, "android.permission.WRITE_EXTERNAL_STORAGE") &&
//                PackageManager.PERMISSION_GRANTED ==
//                        ContextCompat.checkSelfPermission(this, "android.permission.READ_EXTERNAL_STORAGE")) {
//            prepareSDCardData();
//        } else {
//            ActivityCompat.requestPermissions(this, new String[]{"android.permission.WRITE_EXTERNAL_STORAGE",
//                    "android.permission.READ_EXTERNAL_STORAGE"}, 10);
//        }
//    }
//    @Deprecated
//    boolean initiated = false;
//    @Deprecated
//    private void prepareSDCardData() {
//        File path = new File(ScreenCaptureService.trainInitPath + File.separator + "tessdata");
//        if (!path.exists()) {
//            path.mkdirs();
//        }
//        File file = new File(path, ScreenCaptureService.trainFileName);
//        if (!file.exists()) {
//            try {
//                file.createNewFile();
//                byte[] bytes = readRawTrainingData(this);
//                FileOutputStream fileOutputStream = new FileOutputStream(file);
//                fileOutputStream.write(bytes);
//                fileOutputStream.close();
//                initiated = true;
//            } catch (FileNotFoundException e) {
//                e.printStackTrace();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        } else {
//            initiated = true;
//        }
//
//    }
//    @Deprecated
//    private byte[] readRawTrainingData(Context context) {
//        try {
//            InputStream fileInputStream = context.getResources()
//                    .openRawResource(R.raw.chi_sim);
//            ByteArrayOutputStream bos = new ByteArrayOutputStream();
//            byte[] b = new byte[1024];
//            int bytesRead;
//            while ((bytesRead = fileInputStream.read(b)) != -1) {
//                bos.write(b, 0, bytesRead);
//            }
//            fileInputStream.close();
//            return bos.toByteArray();
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        return null;
//    }
    //***********准备区域
    //***********识别区域

//        private void initTess(){
//            baseApi = new TessBaseAPI();
//            baseApi.init(trainInitPath, "chi_sim");
//        }
//    private void processImageToText(Bitmap bitmap){
//            if(baseApi==null){
//                initTess();
//            }
    // 开始调用Tess函数对图像进行识别
//            baseApi.setImage(bitmap);
//            Task<Text> result =recognizer.process(bitmap,0)
//                    .addOnSuccessListener(new OnSuccessListener<Text>() {
//                        @Override
//                        public void onSuccess(Text text) {
//                            // Task completed successfully
//                            // ...
////                            Log.e(TAG, "onSuccess: "+text.getText() );
//                        }
//                    })
//                    .addOnFailureListener(
//                            new OnFailureListener() {
//                                @Override
//                                public void onFailure(@NonNull Exception e) {
//                                    // Task failed with an exception
//                                    // ...
////                                    Log.e(TAG, "onFailure: "+e.getMessage() );
//                                }
//                            });

//            return baseApi.getUTF8Text();
//    }
    //***********识别区域
    //*************************************tess-two方式的图文识别准备（已弃用）*************************************
}